/**
 * Created by Administrator on 2017/6/6.
 */
import {loginMd} from 'store/modules/types';
import {callAuthCode, callAuthLogin} from 'api/manager/login_api'
import router from 'router/index'
import Storage from 'util/lib/storage'
import {isEmptyObject} from 'util/lib/remex'

const state = {
  loginDetail:{
    userPhone: null,
    captcha: null,
    user: {
      userName: '',
      userToken: ''
    }
  }
}

// getters
const getters = {
  loginDetailStatus: state => state.loginDetail
}

// actions
const actions = {
  // 管理员手机号同步
  [loginMd.A.GET_PHONE]({commit, state},phone) {
    commit(loginMd.GET_PHONE,phone);
  },
  // 管理员验证码同步
  [loginMd.A.GET_CAPTCHA]({commit, state}, captcha) {
    commit(loginMd.GET_CAPTCHA,captcha);
  },
  // 用户登陆
  [loginMd.A.QUICK_LOGIN]({commit, state},userInfo={}) {
    return new Promise(async (resolve, reject) => {
      try {
        const userData = await callAuthLogin(userInfo.userPhone,userInfo.captcha);
        if(!isEmptyObject(userData) && !!userData.user.userToken) {
          Storage.set("managerUserToken", userData.user.userToken)
          commit(loginMd.GET_USER_INFO,userData.user)
          router.push({name: 'MHome'})
        }
        resolve();
      }catch (error) {
        reject(error);
      }
    })
  },
  // 获取验证码
  [loginMd.A.GET_AUTH_CODE]({commit, state}, phone) {
    return new Promise(async (resolve, reject) => {
      try{
        const codeData = await callAuthCode(phone);
        resolve();
      }catch(error) {
        reject(error);
      }
    })
  }
}

// mutations
const mutations = {
  [loginMd.GET_PHONE](state, phone) {
    state.loginDetail.userPhone = phone;
  },
  [loginMd.GET_CAPTCHA](state, captcha) {
    state.loginDetail.captcha = captcha;
  },
  [loginMd.GET_USER_INFO](state, userInfo) {
    state.loginDetail.user = userInfo;
  }
}

export default {
  state,
  getters,
  actions,
  mutations
}
